/**
 * 
 */
package com.johnny.xia.filetest;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author johnnyxia
 *
 */
public class NginxLogCurrent{
    
   static Logger log = LoggerFactory.getLogger(NginxLogCurrent.class);
    
//    public static void main(String[] args){
//        String s = "http://log-mshk.baozun.cn/frontend1/daily.log.";//2016-11-23.log.gz
//        for(int i=1;i<=31;i++){
//            if(i < 10){
//                System.out.println(s+"2016-12-0"+i+".log.gz");
//            }else{
//                System.out.println(s+"2016-12-"+i+".log.gz"); 
//            }
//        }
//        
//    }
    
    static String patten = "03/Jan/2017:\\d\\d:\\d\\d:\\d\\d";
    static Pattern pattern = Pattern.compile(patten);
    
    public static void main(String[] args){
        String file="C:\\mclog\\20170103\\nginx\\oauth.log";
//        
////        String string = readFileByLines2(file);
////        AppendToFile.appendMethodA(path2, string);
//        
//        String data = "47.90.57.55 - - [03/Jan/2017:00:07:01 +0800] 302 \"GET /oauth/microsoftLiveLogin HTTP/1.1\"";
//       String time = regexpGetTime(data);
//       Date start = str2date("2017-01-03 "+time);
//       
//       String data2 = "47.90.57.55 - - [03/Jan/2017:00:07:01 +0800] 302 \"GET /oauth/microsoftLiveLogin HTTP/1.1\"";
//       String time2 = regexpGetTime(data2);
//       Date end = str2date("2017-01-03 "+time2);
//       
//       System.out.println(isConcurrency(start, end));
        
        readFileByLines3(file);
        
    }
    
    public static int isConcurrency(Date start,Date end){
       if((end.getTime() - start.getTime()) == 0){
           return 0;
       }else if(end.getTime() - start.getTime() == 1000){
           return 1;
       }else{
           return 2;
       }
    }
    
    public static Date str2date(String str){
        
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try{
            Date date = format.parse(str);
            return date;
        }catch (ParseException e){
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
    
    public static String regexpGetTime(String data){
        String time = "";
        Matcher matcher = pattern.matcher(data); 
        while (matcher.find()) {
            time = matcher.group(0);
        }
        
        return time.split("2017:")[1];
    }
    
    
    /**
     * 间隔很近的请求
     */
    public static Map<String,List<String>> readFileByLines3(String fileName){
        Set<String> set = new LinkedHashSet<>();
        Map<String,List<String>> map = new HashMap<>();
        
        StringBuffer buffer = new StringBuffer();

        File file = new File(fileName);
        BufferedReader reader = null;
        
        String previousLine = null;
        try{
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            // 一次读入一行，直到读入null为文件结束
            while ((tempString = reader.readLine()) != null){
                if(previousLine != null){
                    String time = regexpGetTime(previousLine);
                    Date start = str2date("2017-01-03 "+time);
                    
                    String time2 = regexpGetTime(tempString);
                    Date end = str2date("2017-01-03 "+time2);
                    
                    if(isConcurrency(start, end) < 2 
                                    && previousLine.contains("/oauth/microsoftLiveCallback") 
                                    && tempString.contains("/oauth/microsoftLiveCallback")){
                        
                        log.info(time);
                        log.info(time2);

                        set.add(previousLine);
                        set.add(tempString);
                    }
                }
                previousLine = tempString;
            }
            reader.close();
        }catch (IOException e){
            e.printStackTrace();
        }finally{
            if (reader != null){
                try{
                    reader.close();
                }catch (IOException e1){}
            }
        }
        
        
        for(String s : set){
            System.out.println(s);
        }
        
        return null;
    }
    
    /**
     * 以行为单位读取文件，常用于读面向行的格式化文件
     */
    public static String readFileByLines2(String fileName){

        StringBuffer buffer = new StringBuffer();

        File file = new File(fileName);
        BufferedReader reader = null;
        try{
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            // 一次读入一行，直到读入null为文件结束
            while ((tempString = reader.readLine()) != null){
                if(!tempString.contains("GET /oauth")){
                    continue;
                }
                buffer.append(splitStr(tempString)).append("\r\n");
               
            }
            reader.close();
        }catch (IOException e){
            e.printStackTrace();
        }finally{
            if (reader != null){
                try{
                    reader.close();
                }catch (IOException e1){}
            }
        }
        return buffer.toString();
    }

    /**
     * 以行为单位读取文件，常用于读面向行的格式化文件
     */
    public static Map<String,List<String>> readFileByLines(String fileName){

        Map<String,List<String>> map = new HashMap<>();
        
        StringBuffer buffer = new StringBuffer();

        File file = new File(fileName);
        BufferedReader reader = null;
        try{
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            // 一次读入一行，直到读入null为文件结束
            while ((tempString = reader.readLine()) != null){
//                if(!isok(tempString)){
//                    continue;
//                }
//                buffer.append(splitStr(tempString)).append("\r\n");
                
                String[] array = tempString.split(" - - ");
                
                if(map.get(array[0]) == null){
                    List<String> list = new ArrayList<>();
                    list.add(array[1]);
                    map.put(array[0], list);
                }else{
                    map.get(array[0]).add(array[1]);
                }
            }
            reader.close();
        }catch (IOException e){
            e.printStackTrace();
        }finally{
            if (reader != null){
                try{
                    reader.close();
                }catch (IOException e1){}
            }
        }
        return map;
    }
    
    public static boolean isok(String str){
        
        if(str.contains("Exception")){
            return false;
        }
        if(str.contains("Log4JLogger.java:449")){
            return false;
        }
        
        if(str.length() < 8){
            return false;
        }
        
       /* String tmp = str.substring(0,8);
        SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
        try{
            df.parse(tmp);
        }catch (ParseException e){
            return false;
        }
        return true;*/
        
        str = str.replace("2016-12-31 ", "");
        
        String tmp = str.substring(0,8);
        SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
        try{
            df.parse(tmp);
        }catch (ParseException e){
            return false;
        }
        return true;
    }
    
    public static String splitStr(String str){
        if(str.contains("PaymentController.java:472")){
            return str.split("\\,address")[0];
        }else if(str.contains("PaymentController.java:197")){
            return str.split("\\,result")[0];
        }else if(str.contains("PaymentController.java:250")){
            return str.split("\\,value")[0];
        }else if(str.contains("PaymentController.java:214")){
            return str.split("\\,result")[0];
        }else if(str.contains("PaymentController.java:223")){
            return str.split("\\,value")[0];
        }else if(str.contains("PaymentController.java:250")){
            return str.split("\\,value")[0];
        }
        return str;
    }
    
    public static void fw(String file ,String s){
        FileOutputStream out = null;   

        try {   

            out = new FileOutputStream(new File(file));   
                out.write(s.getBytes());   
            out.close();   


        }catch(Exception e){
            e.printStackTrace();
        }

    }

}
